package com.nononsenseapps.feeder.ui

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.TextAppearanceSpan
import android.view.*
import android.widget.*
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.gitee.wsl.android.common.ui.activity.filePicker

import com.gitee.wsl.ext.base.isFalse
import com.kunminx.linkage.LinkageRecyclerView
import com.kunminx.linkage.adapter.viewholder.LinkageSecondaryViewHolder
import com.kunminx.linkage.bean.BaseGroupedItem
import com.kunminx.linkage.bean.DefaultGroupedItem
import com.kunminx.linkage.defaults.DefaultLinkagePrimaryAdapterConfig
import com.kunminx.linkage.defaults.DefaultLinkageSecondaryAdapterConfig
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView

import com.lxj.xpopup.interfaces.OnInputConfirmListener
import com.nononsenseapps.feeder.db.ARG
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.db.room.upsert
import com.nononsenseapps.feeder.imageloader.displayImage
import com.nononsenseapps.feeder.ui.base.CoroutineScopedActivity
import com.nononsenseapps.feeder.ui.base.IMPORT_OPML_CODE
import com.nononsenseapps.feeder.ui.common.filepicker.MyFilePickerActivity

import com.nononsenseapps.feeder.ui.common.xpopup.XPopupExt
import com.nononsenseapps.feeder.util.*
import com.nononsenseapps.feeder.worker.syncFeed
import com.nononsenseapps.filepicker.AbstractFilePickerActivity
import com.nononsenseapps.jsonfeed.Feed
import com.nononsenseapps.jsonfeed.Item
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import timber.log.Timber
import java.net.URL


class FeedNavigationActivity : CoroutineScopedActivity() {

    private lateinit var feedNavigation: LinkageRecyclerView<DefaultGroupedItem.ItemInfo>

    private val navigationViewModel: FeedNavigationViewModel by viewModels()

    private val defaultLinkageSecondaryAdapterConfig  by lazy {  object :DefaultLinkageSecondaryAdapterConfig(){
        override fun onBindViewHolder(holder: LinkageSecondaryViewHolder?, item: BaseGroupedItem<DefaultGroupedItem.ItemInfo>?) {
            super.onBindViewHolder(holder, item)
            holder?.itemView?.setOnClickListener { viewSelectedFeed(item!!.info) }
        }
      }
    }

    private val defaultLinkagePrimaryAdapterConfig by lazy {  DefaultLinkagePrimaryAdapterConfig() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_feed_navigation)
        setSupportActionBar(findViewById(R.id.nav_toolbar))

        // Not persisted so set nightmode every time we start
        AppCompatDelegate.setDefaultNightMode(settingsViewModel.themePreference)

        feedNavigation=findViewById(R.id.feed_linkage_navigation)
        navigationViewModel.feedViewList.observe(this,Observer{
            val navigationList= mutableListOf<DefaultGroupedItem>()
            val tags= mutableListOf<String>()
            it.forEach {feed->
                val tag=when(feed.tag.isEmpty()){
                    true->"no tag"
                    else ->feed.tag
                }
                tags.contains(tag).isFalse {
                    tags.add(tag)
                    navigationList.add(DefaultGroupedItem(true,tag))
                }
                navigationList.add(DefaultGroupedItem(DefaultGroupedItem.ItemInfo(feed.title,tag,feed.url.toString())))
            }

            feedNavigation.init(navigationList as List<BaseGroupedItem<DefaultGroupedItem.ItemInfo>>,defaultLinkagePrimaryAdapterConfig,defaultLinkageSecondaryAdapterConfig)
        })


        val i = intent
        if (i != null) {
            // Link
            i.getStringExtra(ARG.LINK)?.let {
                navigationViewModel.syncFromNet(it)
            }
        }

    }

    override fun onCreateOptionsMenu(menu: Menu):Boolean {
        menuInflater.inflate(R.menu.feed_navigation, menu)
        return true
    }



    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.action_open_opml_net->{
                 /*XPopup.Builder(this)
                  .asInputConfirm("打开在线OPML", "请输入URL地址。",PrefUtils.getFeedNavigationUrl(this),"https://www.opml.cn/feed") {
                     it.isNotEmpty().isTrue {
                         PrefUtils.setFeedNavigationUrl(this,it)
                         loadingPop.show()
                         navigationViewModel.syncFromNet(it)
                         loadingPop.dismiss()
                     }
                 }.show()*/

                val confirmListener= OnInputConfirmListener {
                    it.isNotEmpty().isTrue {
                        PrefUtils.setFeedNavigationUrl(this,it)
                        loadingPop.show()
                        navigationViewModel.syncFromNet(it)
                        loadingPop.dismiss()
                    }
                }
                XPopupExt.asInputConfirm(this,"打开在线OPML", "请输入URL地址。",
                    PrefUtils.getFeedNavigationUrl(this),
                    storePropName = OPML_HOSTORY_LIST_PROP_NAME,
                    hint = "https://www.opml.cn/feed", confirmListener = confirmListener)
                    .show()
                return true
            }
            R.id.action_open_opml_local->{
                // Choose file
//                val intent: Intent
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                    intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
//                    intent.addCategory(Intent.CATEGORY_OPENABLE)
//                    intent.type = "*/*"
//                    intent.putExtra(Intent.EXTRA_MIME_TYPES,
//                            arrayOf("text/plain", "text/xml", "text/opml", "*/*"))
//                } else {
//                    intent = Intent(application,  MyFilePickerActivity::class.java)
//                    intent.putExtra(AbstractFilePickerActivity.EXTRA_SINGLE_CLICK, true)
//                }
//                startActivityForResult(intent, IMPORT_OPML_CODE)

                filePicker("feeder.opml", arrayOf("text/plain", "text/xml", "text/opml", "*/*")){
                    it?.let {
                        navigationViewModel.openWithLocal(it)
                    }
                }

                return true
            }
            R.id.action_net_online->{
                navigationViewModel.feedFilterWithNetConnectedCheck(1)
            }
            R.id.action_host_exclude->{
                XPopup.Builder(this).isDarkTheme(PrefUtils.isNightMode(this)).asInputConfirm("主站排除","输入要排除的站点名称"){
                    navigationViewModel.feedHostFilter(it)
                }.show()
            }
        }
        return super.onContextItemSelected(item)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        when (requestCode) {
            IMPORT_OPML_CODE ->
                 data?.data?.let {
                     navigationViewModel.openWithLocal(it)
                 }
        }
    }

    fun viewSelectedFeed(item:DefaultGroupedItem.ItemInfo){
        loadingPop.show()
        lifecycleScope.launch(Dispatchers.IO) {
            syncFeed(feedParser, URL(item.content),5L){
                lifecycleScope.launch(Dispatchers.Main) {
                    loadingPop.isShow.isTrue {
                        loadingPop.dismiss()
                    }
                    Toast.makeText(this@FeedNavigationActivity, "load error:${item.title}", Toast.LENGTH_SHORT).show()
                }
            }?.let {feed->
                withContext(Dispatchers.Main){
                    Timber.d("load feed from net:${feed.title}\turl:${feed.feed_url}\tsize:${feed.items?.size}")
                    loadingPop.isShow.isTrue {
                        loadingPop.dismiss()
                    }
                    XPopup.Builder(this@FeedNavigationActivity)
                            .dismissOnBackPressed(true)
                            .asCustom(ViewFeedDrawerPopup(this@FeedNavigationActivity, feed, actionCallBack = object:FeedDrawerPopupActionCallBack{
                                override fun installFeed(feed: com.nononsenseapps.feeder.db.entity.Feed) {
                                    lifecycleScope.launch(Dispatchers.IO) {
                                        feedDao.upsert(feed)
                                    }
                                }
                                override fun isExitsFeed(url:String): Boolean = runBlocking(Dispatchers.IO) {
                                        feedDao.isExitsFeed(url)
                                    }
                            }))
                            .show()
                }
            }
        }
    }

    companion object{
        val OPML_HOSTORY_LIST_PROP_NAME="XPopupExt.mutableOpmlList"
    }
}

interface FeedDrawerPopupActionCallBack{
    fun installFeed(feed: com.nononsenseapps.feeder.db.entity.Feed)
    fun isExitsFeed(url:String):Boolean
}

class ViewFeedDrawerPopup(context: Context, var feed: Feed,val actionCallBack:FeedDrawerPopupActionCallBack) : BottomPopupView(context){

    lateinit var addButton:View
    lateinit var feedTextView:TextView
    lateinit var recyclerView:ListView

    private val feedItemAdapter by lazy {
        object:ArrayAdapter<Item>(context,R.layout.list_story_item_normal,R.id.story_snippet){
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val viewHolder= super.getView(position, convertView, parent)
                val item=getItem(position)
                val imageView  = viewHolder.findViewById<ImageView>(R.id.story_image)
                imageView.visibility=View.GONE
                item?.let{
                val pubDate =
                        try {
                            // Allow an actual pubdate to be updated
                            DateTime.parse(item.date_published)
                        } catch (t: Throwable) {
                            // If a pubdate is missing, then don't update if one is already set
                            DateTime.now(DateTimeZone.UTC)
                        }

                viewHolder.findViewById<TextView>(R.id.story_date).text= DateUtils.timeAlong(pubDate.toDate())
                viewHolder.findViewById<TextView>(R.id.story_author).text=item.author?.name

                val title=item.title?:""
                val temps = if (item.summary.isNullOrEmpty())
                    title
                else
                    title + " \n.\t\t" + item.summary + "\u2026"
                val textSpan = SpannableString(temps)

                textSpan.setSpan(TextAppearanceSpan(parent.context, R.style.TextAppearance_ListItem_Body),
                        title.length, temps.length,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                textSpan.setSpan(TextAppearanceSpan(parent.context, R.style.TextAppearance_ListItem_Title),
                        0, title.length,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

                viewHolder.findViewById<TextView>(R.id.story_snippet).text=textSpan

                if(item.image?.isNotEmpty()==true) {
                    imageView.visibility=View.VISIBLE
                    displayImage(context, item.image, imageView)
                }
                }
                return viewHolder
            }
        }
    }

    override fun getImplLayoutId(): Int {
        return R.layout.popup_view_feed_drawer
    }

    override fun onCreate() {
        super.onCreate()
        findViewById<View>(R.id.imageButton_close).setOnClickListener { dismiss() }
        feedTextView=findViewById(R.id.textView_feedName)
        addButton=findViewById(R.id.button_add_feed)
        addButton.setOnClickListener {
            feed.let{
                val feedSql = com.nononsenseapps.feeder.db.entity.Feed(
                    ID_UNSET,
                    title = it.title ?: "",
                    customTitle = it.title ?: "",
                    url = URL(it.feed_url)
                )
                actionCallBack.installFeed(feedSql)
            }
            dismiss()
        }
        recyclerView = findViewById(R.id.feed_item_recyclerView)
        recyclerView.adapter = feedItemAdapter

        feedTextView.text = feed.title
        feed.items?.let { it1 -> feedItemAdapter.addAll(it1) }
        feed.feed_url?.let { url ->
            actionCallBack.isExitsFeed(url).let {
                addButton.visibility =if(it)  View.GONE else View.VISIBLE
            }
        }
    }

}
